﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using YanhuaMMO;

public class TBSReportEditor : EditorWindow
{
	public class CMD
	{
		public int frame = 0;
		public int cid = 0;
		public string cmd = "";
		public string active = "";
		public int action = 0;
		public CMD(string cmd)
		{
			this.cmd = cmd;
			int cid = int.Parse(GetValue("cid"));
			int frame = int.Parse(GetValue("frame"));
			int action = int.Parse(GetValue("action"));
			this.cid = cid;
			this.frame = frame;
			this.action = action;
		}
		public string GetValue(string key)
		{
			int start = cmd.IndexOf(key);
			if (start < 0) return "";
			start = start + key.Length +1;
			int end = cmd.IndexOf(',', start);
			if (end < 0) return "";
			return cmd.Substring(start, end - start);
		}
		public bool IsTurnNode()
		{
			return action == 101;
		}
		public bool MyTurn()
		{
			return action == 101;
		}
	}
	[MenuItem("Tools/战报播放(组队战)",false,0)]
	public static void OpenWindow()
	{
		GetWindow<TBSReportEditor>(false, "战报播放(组队战)",true).Show();
	}
	private string reportPathFile;
	private const string ZHANBAO_PATH_KEY = "tbs_report_zhanbao_local_path";
	private bool isStartFight = false;
	private SortedDictionary<int, CMD> cmdDic = new SortedDictionary<int,  CMD>();
	private SortedDictionary<int, SortedDictionary<int, CMD>> frameDic = new SortedDictionary<int, SortedDictionary<int, CMD>>();
	private SortedDictionary<int, string> activeDic = new SortedDictionary<int, string>();
	

	private GUIStyle redStyle;
	private int turnCount = 0;
	private Vector2 scrollPos;
	private Vector2 activeScrollPos;
	private bool isScrollFoldOut = false;
	private bool isCurCmdFoldOut = true;
	private int frameFoldOut = 0;
	private int width = 900;
	void OnEnable()
	{
		reportPathFile = PlayerPrefs.GetString(ZHANBAO_PATH_KEY, "");
		turnCount = 0;
		isScrollFoldOut = false;
		isCurCmdFoldOut = true;
		frameFoldOut = 0;
	}
	private void OnGUI()
	{
		if (redStyle == null)
		{
			redStyle = new GUIStyle();
			redStyle.normal.textColor = Color.green;
		}
		EditorGUILayout.Space();
		GUILayout.BeginHorizontal(GUILayout.MaxWidth(width));
		EditorGUILayout.LabelField("战报文件",GUILayout.Width(50));
		reportPathFile = EditorGUILayout.TextField("", reportPathFile);
		if (GUILayout.Button("选择", GUILayout.MaxWidth(80)))
		{
			string dir = Application.dataPath + "";
			if (!string .IsNullOrEmpty(reportPathFile))
			{
				dir = Path.GetDirectoryName(reportPathFile);
			}

			string path = UnityEditor.EditorUtility.OpenFilePanel("Load Images of Directory", dir, "*");
			if (path == "")
				return;
			reportPathFile = path;
			//缓存位置
			PlayerPrefs.SetString(ZHANBAO_PATH_KEY, reportPathFile);
		}
		GUILayout.EndHorizontal();
		EditorGUILayout.Space();
		GUILayout.BeginHorizontal();
		if (GUILayout.Button("播放战报", GUILayout.MaxWidth(width)))
		{
			if (string.IsNullOrEmpty(reportPathFile))
			{
				EditorUtility.DisplayDialog("", "先选择战报", "确定");
				return;
			}
			if (!Application.isPlaying)
			{
				EditorUtility.DisplayDialog("", "先运行游戏", "确定");
				return;
			}
			PlayReport();
		}
		GUILayout.EndHorizontal();
		EditorGUILayout.Space();
		if (!Application.isPlaying) return;
		if (isStartFight)
		{
			if(cmdDic.Count == 0)
			{
				InitReportCmd();
			}
			else
			{
				turnCount = GetCurTurn();
			}
		}
		else
		{
			isStartFight = IsPlaying();
			turnCount = 0;
			cmdDic.Clear();
		}
		
		isScrollFoldOut = EditorGUILayout.Foldout(isScrollFoldOut, "总指令:(当前回合：" + turnCount + ")");
		EditorGUILayout.Space();
		if (isScrollFoldOut)
		{
			scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(width), GUILayout.Height(500));
			foreach (var v in frameDic)
			{
				string active = "";
				
				bool foldOut = EditorGUILayout.Foldout(frameFoldOut == v.Key, "第" + v.Key + "回合");
				if (foldOut)
				{
					frameFoldOut = v.Key;
					foreach (var cmd in v.Value)
					{
						bool flag = activeDic.TryGetValue(cmd.Key, out active);
						if (flag)
							EditorGUILayout.TextField(cmd.Value.cmd, redStyle);
						else
							EditorGUILayout.TextField(cmd.Value.cmd);
					}
				}
				else
				{
					if(frameFoldOut == v.Key)
					{
						frameFoldOut = 0;
					}
				}
			}
			/*foreach (var v in cmdDic)
			{
				string active = "";
				bool flag = activeDic.TryGetValue(v.Key, out active);
				if (flag)
					EditorGUILayout.TextField(v.Value.cmd, redStyle);
				else
					EditorGUILayout.TextField(v.Value.cmd);

			}*/
			EditorGUILayout.EndScrollView();
		}
		isCurCmdFoldOut = EditorGUILayout.Foldout(isCurCmdFoldOut, "当前指令:(当前回合：" + turnCount + ")");
		EditorGUILayout.Space();
		activeDic.Clear();
		if (cmdDic.Count > 0)
		{
			InitCmdState();
			if (isCurCmdFoldOut)
			{
				if (activeDic.Count > 10)
				{
					activeScrollPos = EditorGUILayout.BeginScrollView(activeScrollPos, GUILayout.Width(width), GUILayout.Height(300));
				}
				foreach (var v in activeDic)
				{
					bool flag = cmdDic.TryGetValue(v.Key, out CMD cmd);
					if (flag)
						EditorGUILayout.TextField( v.Value + cmd.cmd, redStyle);

				}
				if (activeDic.Count > 10)
				{
					EditorGUILayout.EndScrollView();
				}

			}
		}
	}

	private void PlayReport()
	{
		string report = "";
		StreamReader sr = null;
		try
		{
			sr = new StreamReader(reportPathFile);
			report = sr.ReadToEnd();
			Util.CallMethod("TBS.VirtualServer", "EditorPlayReport", report);
			isStartFight = false;
			turnCount = 0;
			cmdDic.Clear();
		}
		catch (Exception e)
		{
			Debug.LogError(e.StackTrace);
		}
		finally
		{
			if (sr != null)
				sr.Close();
		}
	}

	private int GetCurTurn()
	{
		int count = 0;
		var obj = Util.CallMethod("TBS.VirtualServer", "EditorGetCurTurn");
		if (obj != null && obj.Length > 0 && obj[0] != null)
		{
			string s = obj[0].ToString();
			count = int.Parse(s);
		}
		return count;
	}
	private void InitReportCmd()
	{
		frameDic.Clear();
		var obj = Util.CallMethod("TBS.VirtualServer", "EditorGetReportCmd");
		if (obj == null || obj.Length == 0 || obj[0] == null)
			return;
		string str = (string)obj[0];
		if (string.IsNullOrEmpty(str)) return;
		var _list = str.Split('|');
		for (int i = 0; i < _list.Length; i++)
		{
			string s = _list[i];
			if (s == "") continue;
			CMD cmd = new CMD(s);
			cmdDic.Add(cmd.cid,cmd);
			SortedDictionary<int, CMD> dic;
			bool flag = frameDic.TryGetValue(cmd.frame,out dic);
			if (!flag)
			{
				dic = new SortedDictionary<int, CMD>();
				frameDic.Add(cmd.frame, dic);
			}
			dic.Add(cmd.cid, cmd);
		}
	}
	private bool IsPlaying()
	{
		bool isPlaying = false;
		var obj = Util.CallMethod("TBS.VirtualServer", "EditorIsPlaying");
		if (obj != null && obj.Length > 0 && obj[0] != null)
		{
			isPlaying = (bool)obj[0];
		}
		return isPlaying;
	}
	private void InitCmdState()
	{
		activeDic.Clear();
		var obj = Util.CallMethod("TBS.VirtualServer", "EditorGetCmdState");
		if (obj != null && obj.Length > 0 && obj[0] != null)
		{
			string s = obj[0].ToString();
			if (s != "")
			{
				string[] a = s.Split('|');
				for (int i = 0; i < a.Length; i++)
				{
					if (a[i] == "") continue;
					string[] v = a[i].Split(',');
					int cid = int.Parse(v[0]);
					string active = v[1];
					activeDic.Add(cid, active);
				}
			}
		}
	}
}
